#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import logging
import sys
import json
import os
import time
import requests
import random
import dpkt
import socket
from ipaddress import ip_address

ip_path = os.path.join(os.path.abspath(os.path.dirname(__file__)).split('zhang-mock')[0],
                       "zhang-mock/data/fakerData/ip_10_w.txt")
et1_req = os.path.join(os.path.abspath(os.path.dirname(__file__)).split('zhang-mock')[0],
                       "zhang-mock/data/event_template/event_template_1_req.txt")
et1_rsp = os.path.join(os.path.abspath(os.path.dirname(__file__)).split('zhang-mock')[0],
                       "zhang-mock/data/event_template/event_template_1_rsp.txt")
et2_req = os.path.join(os.path.abspath(os.path.dirname(__file__)).split('zhang-mock')[0],
                       "zhang-mock/data/event_template/event_template_2_req.txt")
et2_rsp = os.path.join(os.path.abspath(os.path.dirname(__file__)).split('zhang-mock')[0],
                       "zhang-mock/data/event_template/event_template_2_rsp.txt")
et3_req = os.path.join(os.path.abspath(os.path.dirname(__file__)).split('zhang-mock')[0],
                       "zhang-mock/data/event_template/event_template_3_req.txt")
et3_rsp = os.path.join(os.path.abspath(os.path.dirname(__file__)).split('zhang-mock')[0],
                       "zhang-mock/data/event_template/event_template_3_rsp.txt")
et4_req = os.path.join(os.path.abspath(os.path.dirname(__file__)).split('zhang-mock')[0],
                       "zhang-mock/data/event_template/event_template_4_req.txt")
et4_rsp = os.path.join(os.path.abspath(os.path.dirname(__file__)).split('zhang-mock')[0],
                       "zhang-mock/data/event_template/event_template_4_rsp.txt")
et5_req = os.path.join(os.path.abspath(os.path.dirname(__file__)).split('zhang-mock')[0],
                       "zhang-mock/data/event_template/event_template_5_req.txt")
et5_rsp = os.path.join(os.path.abspath(os.path.dirname(__file__)).split('zhang-mock')[0],
                       "zhang-mock/data/event_template/event_template_5_rsp.txt")
pcap_name = "hacker"


def get_file(file_path):
    try:
        with open(file_path, "rb") as detail:
            file_details = detail.read()

    except IOError:
        logging.error('Input File Not Found')
        exit()
    return file_details


class SendMessage(object):

    def __init__(self):
        # 模板内容实例化进来
        self.req1 = get_file(et1_req)
        print(type(self.req1))
        self.rsp1 = get_file(et1_rsp)
        self.req2 = get_file(et2_req)
        self.rsp2 = get_file(et2_rsp)
        self.req3 = get_file(et3_req)
        self.rsp3 = get_file(et3_rsp)
        self.req4 = get_file(et4_req)
        self.rsp4 = get_file(et4_rsp)
        self.req5 = get_file(et5_req)
        self.rsp5 = get_file(et5_rsp)


    @staticmethod
    def get_ip_list(file_path=ip_path):
        # 获取IP列表
        try:
            with open(file_path, "r") as ip:
                tool_list = ip.readline()
                # ip_list = list(tool_list[0])
                ip_list = eval(tool_list)
        except IOError:
            logging.error('Input File Not Found')
            exit()
        return ip_list

    def event_template01(self):
        test_url = "http://jf365.boc.cn:5555/BOCVIP/pages/noticeMessage/user_content_message_list.html"
        header = {
            "Host": "jf365.boc.cn",
            "Connection": "keep - alive",
            "User-Agent": "Mozilla / 5.0(Macintosh;Intel Mac OS X 10_15_7) AppleWebKit/"
                          "537.36(KHTML, like Gecko) Chrome / 91.0.4472.114 Safari / 537.36",
            "Accept": "* / *",
            "Referer": "https://jf365.boc.cn/BOCVIP/defaultIndex.do"
        }
        resp = requests.request("GET", url=test_url, headers=header)
        # print(resp.text)
        logging.info(resp)

    def event_template02(self):
        test_url = "http://jf365.boc.cn:5555/BOCGIFTNET/ajaxData/ajaxGetPicUrl.do"
        header = {
            "Host": "jf365.boc.cn",
            "Connection": "keep - alive",
            "User-Agent": "Mozilla/5.0(Macintosh;Intel Mac OS X 10_15_7) AppleWebKit/"
                          "537.36(KHTML, like Gecko) Chrome / 91.0.4472.114 Safari / 537.36",
            "Accept": "* / *",
            "Referer": "https://jf365.boc.cn/BOCGIFTNET/defaultIndex.do"
        }
        param = "picurl=giftpicurl&_=1627530571937 HTTP/1.1"
        resp = requests.request("GET", url=test_url, headers=header, params=param)
        print(resp.text)
        logging.info(resp)

    def event_template03(self):
        test_url = "http://jf365.boc.cn:5555/BOCGIFTNET/ajaxMember/ajaxNoticesData.do"
        header = {
            "Host": "jf365.boc.cn",
            "Connection": "keep - alive",
            "User-Agent": "Mozilla/5.0(Macintosh;Intel Mac OS X 10_15_7) AppleWebKit/"
                          "537.36(KHTML, like Gecko) Chrome / 91.0.4472.114 Safari / 537.36",
            "Accept": "* / *",
            "Referer": "https://jf365.boc.cn/BOCGIFTNET/defaultIndex.do"
        }
        param = "token=c5c9453a84f54fb48b704b94a114ae03&r=0.2111083263002811&_=1627530571938"
        resp = requests.request("GET", url=test_url, headers=header, params=param)
        # print(resp.text)
        logging.info(resp)

    def event_template04(self):
        test_url = "http://jf365.boc.cn:5555/BOCGIFTNET/ajaxData/ajaxSyncToken.do"
        header = {
            "Host": "jf365.boc.cn",
            "Connection": "keep - alive",
            "User-Agent": "Mozilla/5.0(Macintosh;Intel Mac OS X 10_15_7) AppleWebKit/"
                          "537.36(KHTML, like Gecko) Chrome / 91.0.4472.114 Safari / 537.36",
            "Accept": "* / *",
            "Referer": "https://jf365.boc.cn/BOCGIFTNET/defaultIndex.do"
        }
        param = "token=c5c9453a84f54fb48b704b94a114ae03&r=0.9666518644987483&_=1627530571939"
        resp = requests.request("GET", url=test_url, headers=header, params=param)
        # print(resp.text)
        logging.info(resp)

    def event_template05(self):
        test_url = "http://jf365.boc.cn:5555/BOCVIP/ajaxMember/ajaxAllNoticeListData.do"
        header = {
            "Host": "jf365.boc.cn",
            "Connection": "keep - alive",
            "User-Agent": "Mozilla/5.0(Macintosh;Intel Mac OS X 10_15_7) AppleWebKit/"
                          "537.36(KHTML, like Gecko) Chrome / 91.0.4472.114 Safari / 537.36",
            "Accept": "* / *",
            "Referer": "https://jf365.boc.cn/BOCVIP/pages/noticeMessage/user_content_message_list.html"
        }
        param = "token=c5c9453a84f54fb48b704b94a114ae03&r=0.9666518644987483&_=1627530571939"
        resp = requests.request("GET", url=test_url, headers=header, params=param)
        # print(resp.text)
        logging.info(resp)

    def create_re2pcap(self, input_req, output, pcap_file="cc_high_fq"):
        url = "http://192.168.0.206:5000/createPcap"
        params = {
            "inputRequest": input_req,
            "inputResponse": output,
            'pcapFileName': pcap_file

        }
        print (params)
        pcaprsp = requests.post(url, params)
        with open(pcap_file + ".pcap", "wb") as f:
            f.write(pcaprsp.content)

    def real_customer(self, count=15, ip=20):

        ip_list = self.get_ip_list()
        customer_ip_list = []

        for i in range(0, 20):
            ip = random.choice(ip_list)
            customer_ip_list.append(ip)
        print(str(customer_ip_list))
        print(time.time())
        for j in range(0, 60):
            counter = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

            for i in range(0, 150):
                ts = 1631930400 + i % 60 + j*60
                print(ts)
                rest = random.randint(1, 5)
                out_put = "./test/cust" + str(150*j+i) + ".pcap"
                print("第" + str(150*j+i) + "次发送："+ out_put + str(rest))
            # out_put = "./test/cust" + str(i) + ".pcap"
            # 每分钟不大于 15次
            # sip = ""
                ip_rest = random.randint(0, 19)
                while counter[ip_rest] >= 15:
                    ip_rest = random.randint(0, 19)
                counter[ip_rest] = counter[ip_rest] + 1
                sip = customer_ip_list[ip_rest]

                if rest == 1:
                    #self.event_template01()
                    # self.create_re2pcap(input_req=self.req1, output=self.rsp1, pcap_file="temp1")
                    self.edit_pcap("temp1.pcap", output_pcap=out_put, sip=sip, dip=sip, ts=ts)
                elif rest == 2:
                    # self.create_re2pcap(input_req=self.req2, output=self.rsp2, pcap_file="temp2")
                    # self.event_template02()
                    self.edit_pcap("temp2.pcap", output_pcap=out_put, sip=sip, dip=sip, ts=ts)
                elif rest == 3:
                    self.edit_pcap("temp3.pcap", output_pcap=out_put, sip=sip, dip=sip, ts=ts)
                    # self.create_re2pcap(input_req=self.req3, output=self.rsp3, pcap_file="temp3")
                    # self.event_template03()
                elif rest == 4:
                    # self.create_re2pcap(input_req=self.req4, output=self.rsp4, pcap_file="temp4")
                    # self.event_template04()
                    self.edit_pcap("temp4.pcap", output_pcap=out_put, sip=sip, dip=sip, ts=ts)
                elif rest == 5:
                    # self.event_template05()
                    self.edit_pcap("temp5.pcap", output_pcap=out_put, sip=sip, dip=sip, ts=ts)
                    # self.create_re2pcap(input_req=self.req5, output=self.rsp5, pcap_file="temp5")
                time.sleep(0.02)
        print(time.time())

    def real_hacker(self, count=15, ip=50):
        ip_list = self.get_ip_list()
        customer_ip_list = []
        tm = 1631931600
        for i in range(0, 50):
            ip = random.choice(ip_list)
            customer_ip_list.append(ip)

            for j in range(0, 20):
                for k in range(0, 10):
                    ts = tm + 60*j + 6*k
                    print(ip + "_第" + str(10 * j + k) + "次发送：")
                    print(ts)
                    out_put3 = "./test/hack3" + str(i) + str(10 * j + k) + ".pcap"
                    out_put4 = "./test/hack4" + str(i) + str(10 * j + k) + ".pcap"
                    self.edit_pcap("temp3.pcap", output_pcap=out_put3, sip=ip, dip=ip, ts=ts)
                    self.edit_pcap("temp4.pcap", output_pcap=out_put4, sip=ip, dip=ip, ts=ts)
        print(str(customer_ip_list))


    @staticmethod
    def edit_pcap(input_pcap, output_pcap, sip, dip, ts):
        f = open(input_pcap, 'rb')
        with open(output_pcap, 'wb') as test:
            writer = dpkt.pcap.Writer(test)

            packets = dpkt.pcap.Reader(f)

            for tm, buf in packets:
                eth = dpkt.ethernet.Ethernet(buf)
                ip = eth.data
                tcp =ip.data
                if ip.src==ip_address('10.10.10.1').packed:
                    # zeroes = ip_address(unicode(ips)).packed
                    # ip.src = zeroes
                    eth.data.src = socket.inet_pton(socket.AF_INET, sip)
                if ip.dst==ip_address('10.10.10.1').packed:
                    # zeroes = ip_address(unicode(ips)).packed
                    # ip.dst = zeroes
                    eth.data.dst = socket.inet_pton(socket.AF_INET, dip)
                # eth.data.src = socket.inet_pton(socket.AF_INET, sip)  # 这里是将点分十进制转化成二进制
                # eth.data.dst = socket.inet_pton(socket.AF_INET, dip)
                writer.writepkt(eth, ts=ts)  # 如果不加ts参数的话，这个数据包的时间戳默认是当前时间！
                test.flush()
        f.close()

    def create_pcap_list(self):
        for i in range(0, 150):
            rest = random.randint(1, 5)


if __name__=="__main__":
    sm = SendMessage()
    # sm.real_hacker()
    # sm.real_customer()
    sm.create_re2pcap(sm.req2, sm.rsp2, "temp2gai")
    # sm.event_template01()
    # sm.event_template02()
    # sm.event_template03()
    # sm.event_template04()
    # sm.event_template05()